﻿using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Xunit;

namespace Sgr.IntegrationTests
{
    public class ApplicationFactoryBase<TProgram>
        : WebApplicationFactory<TProgram> where TProgram : class
    {
        protected override IHost CreateHost(IHostBuilder builder)
        {
            //https://github.com/dotnet-architecture/eShopOnWeb/issues/465
            ConfigureHostEnvironment(builder);

            var host = builder.Build();
            host.Start();

            PrepareHost(host);

            return host;
        }

        #region 可重写

        /// <summary>
        /// 配置主机环境
        /// </summary>
        /// <param name="builder"></param>
        protected virtual void ConfigureHostEnvironment(IHostBuilder builder)
        {
            builder.UseEnvironment(Environments.Development);

            builder.ConfigureAppConfiguration((context, conf) =>
            {
                var dict = new Dictionary<string, string?>
                {
                    ["Sgr:BackgroundTasks:AutoStart"] = "false",
                    ["Cors:EnableCors"] = "false"
                };
                conf.AddInMemoryCollection(dict);
            });
        }

        /// <summary>
        /// 完成测试前所需的准备工作
        /// </summary>
        /// <param name="host"></param>
        protected virtual void PrepareHost(IHost host)
        {
        }

        protected virtual Task CleanupHost(IServiceProvider serviceProvider)
        {
            return Task.CompletedTask;
        }

        #endregion 可重写

        #region IAsyncLifetime

        public Task InitializeAsync()
        {
            return Task.CompletedTask;
        }

        public new async Task DisposeAsync()
        {
            await base.DisposeAsync();
        }

        #endregion IAsyncLifetime
    }
}